package com.favccxx.search.api;

import com.favccxx.search.application.DataSetService;
import com.favccxx.search.domain.datasource.dataset.viewobject.DataSetDefinitionVo;
import com.favccxx.search.infrastructure.constant.AppConstants;
import com.favccxx.search.infrastructure.exception.ExceptionCode;
import com.favccxx.search.infrastructure.util.rest.RestResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Api(tags = "3.0 Data Set Interface")
@RequestMapping("/dataset")
@RestController
public class DataSetController {

    @Autowired
    DataSetService dataSetService;

    @ApiOperation("2.1 Load JDBC data sets by data source id.")
    @GetMapping("/jdbc/load")
    public RestResult<List<DataSetDefinitionVo>> loadJdbcDataSets(
            @RequestParam(value = "dataSourceId", required = false) String dataSourceId,
            @RequestParam(value = "dataSourceCode", required = false) String dataSourceCode) {
        if (StringUtils.isNotBlank(dataSourceId)) {
            List<DataSetDefinitionVo> dataList = dataSetService.loadDataSetsByDataSourceId(dataSourceId);
            return RestResult.sucess(dataList);
        }

        if (StringUtils.isNotBlank(dataSourceCode)) {
            List<DataSetDefinitionVo> dataList = dataSetService.loadDataSetsByDataSourceId(dataSourceId);
            return RestResult.sucess(dataList);
        }

        return RestResult.error(ExceptionCode.DataSet.INVALID_PARAMETER, "Invalid parameter, datasouceId and dataSourceCode could not both be null.");
    }

    @ApiOperation("2.2 Save data set definition.")
    @PostMapping("/jdbc/save")
    public RestResult<List<DataSetDefinitionVo>> saveJdbcDataSet(
            @RequestParam(value = "dataSourceId", required = true) String dataSourceId,
            @RequestParam(value = "dataSetNames", required = true) String dataSetNames) {
        if (AppConstants.DEFAULT_SQL_ALL.equals(dataSetNames) || AppConstants.DEFAULT_ALL.equalsIgnoreCase(dataSetNames)) {
            dataSetService.saveAllDataSets(dataSourceId);
            return RestResult.sucess();
        }

        dataSetService.saveJdbcDataSets(dataSourceId, dataSetNames);
        return RestResult.sucess();
    }


}
